package com.polaris.live.utils.image

import android.graphics.Canvas
import android.graphics.ColorFilter
import android.graphics.Rect
import android.graphics.drawable.Drawable
import androidx.annotation.ColorInt
import androidx.annotation.DrawableRes
import androidx.core.app.ActivityCompat
import com.polaris.live.App

/**
 * PlaceholderDrawable
 *
 * @author Created by lucas on 2024/4/9 01:46
 * @since 1.0.0
 */
class PlaceholderDrawable(
    private val originDrawable: Drawable,
    private val percent: Float = 0.6f,
    @ColorInt private val bgColor: Int? = null
) : Drawable() {

    constructor(
        @DrawableRes resId: Int,
        percent: Float = 0.6f,
        @ColorInt bgColor: Int? = null
    ) : this(
        ActivityCompat.getDrawable(App.instance, resId)!!,
        percent,
        bgColor
    )

    private val rect = Rect()

    override fun draw(canvas: Canvas) {
        if (bgColor != null) {
            canvas.drawColor(bgColor)
        }

        originDrawable.draw(canvas)
    }

    override fun setAlpha(alpha: Int) {
        originDrawable.alpha = alpha
    }

    override fun setColorFilter(colorFilter: ColorFilter?) {
        originDrawable.colorFilter = colorFilter
    }

    override fun getOpacity(): Int {
        return originDrawable.opacity
    }

    override fun onLevelChange(level: Int): Boolean {
        if (originDrawable.setLevel(level)) {
            updateLayerBounds(bounds)
            return true
        }
        return super.onLevelChange(level)
    }

    override fun onBoundsChange(bounds: Rect) {
        updateLayerBounds(bounds)
    }

    private fun updateLayerBounds(bounds: Rect) {
        val factor = originDrawable.intrinsicWidth.toFloat() / originDrawable.minimumHeight
        val w: Int
        val h: Int
        if (factor > bounds.width().toFloat() / bounds.height()) {
            w = (bounds.right * percent).toInt()
            h = (w / factor).toInt()
        } else {
            h = (bounds.bottom * percent).toInt()
            w = (h * factor).toInt()
        }

        rect.left = (bounds.width() - w) / 2
        rect.right = rect.left + w
        rect.top = (bounds.height() - h) / 2
        rect.bottom = rect.top + h

        originDrawable.bounds = rect
    }
}